//
//  HomePictureView.swift
//  Weibo
//
//  Created by 郑克哥哥 on 2017/7/29.
//  Copyright © 2017年 郑克哥哥. All rights reserved.
//

import UIKit
import SDWebImage

//配图的间距
private let ItemMargin: CGFloat = 5

//每张配图的宽度
private let ItemWidth = (ScreenWidth - 2 * 10 - 2 * ItemMargin) / 3


//自定义首页配图
class HomePictureView: UICollectionView {
    
    //接收数据源
    var picUrls: [PictureModel]?{
        
        didSet{
            
//            messageLabel.text = "\(picUrls?.count ?? 0)"
            
            //根据图片的数量计算大小,更新配图大小约束
            calculateSize(count: picUrls!.count)
            
            //数据源发生改变重新加载数据
            reloadData()
            
        }
    }
    
    //加载控件
//    fileprivate lazy var messageLabel: UILabel = {
//        
//        let label = UILabel(font: 20, textColor: UIColor.black)
//        
//        return label
//    }()
    

 
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let flowLaout = UICollectionViewFlowLayout()
        
        //图片的宽高是一样的
        flowLaout.itemSize = CGSize(width: ItemWidth, height: ItemWidth)
        //设置列间距
        flowLaout.minimumInteritemSpacing = ItemMargin
        //设置行间距
        flowLaout.minimumLineSpacing = ItemMargin
        
        super.init(frame: frame, collectionViewLayout: flowLaout)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //添加控件 设置约束
    private func setupUI(){
        
        //设置数据源代理
        dataSource = self
        
        //注册cell
        register(HomePictureViewCell.self, forCellWithReuseIdentifier: PictureCell)
        
        //addSubview(messageLabel)
        
//        messageLabel.snp.makeConstraints { (make) in
//            make.center.equalTo(self)
//        }
    }
    
    //根据配图个数计算配图大小
    private func calculateSize(count: Int){
        
        //判断是否是单张图片,使用单张图片作为配图的大小
        if count == 1 {
            
            let imageUrl = picUrls?.first?.thumbnail_pic
            //获取本地单张图片
            if let localImage = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: imageUrl){
                
                var imageSize = localImage.size
                
                //图片过窄处理
                if localImage.size.width < 80{
                    //图片的宽度
                    let imageWidth: CGFloat = 80
                    //图片的高度
                    var imageHeight = imageWidth / localImage.size.width * localImage.size.height
                    
                    //图片过长处理
                    if imageHeight > 150 {
                        //修改图片的高度
                        imageHeight = 150
                    }
                    //计算后的大小
                    imageSize = CGSize(width: imageWidth, height: imageHeight)
                }
                
                //把图片的大小作为配图的大小使用
                self.snp.updateConstraints({ (make) in
                    
                    make.size.equalTo(imageSize).priority(.high)
                })
                
                //把itemSize改成图片的大小
                let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
                
                flowLayout.itemSize = imageSize
                
                return
            }
        }
        
        
        //计算列数(count:配图的数量)
        let cols = count > 3 ? 3:count
        //计算行数(count:配图的数量)
        let rows = (count - 1) / 3 + 1
        
        //计算PictureView的宽度,公式:列数 * 每张图片的宽度 + (列数 - 1) * 每张图片的间距
        let PictureViewWidth = CGFloat(cols) * ItemWidth + CGFloat(cols - 1) * ItemMargin
        //计算PictureView的宽度,公式:行数 * 每张图片的高度(和图片的宽度一样) + (行数 - 1) * 每张图片的间距
        let PictureViewHeight = CGFloat(rows) * ItemWidth + CGFloat(rows - 1) * ItemMargin
        
        //更新配图大小
        self.snp.updateConstraints { (make) in
            //如果约束有优先级,那么在更新约束的时候也要更新优先级
            make.size.equalTo(CGSize(width: PictureViewWidth, height: PictureViewHeight)).priority(.high)
        }
        
        //把itemSize改成图片的大小
        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        flowLayout.itemSize = CGSize(width: ItemWidth, height: ItemWidth)
        
    }

}

//MARK: -------实现数据源方法-------
extension HomePictureView: UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PictureCell, for: indexPath) as! HomePictureViewCell
        
        //赋值图片模型数据
        cell.homePic = picUrls![indexPath.item]
        
        return cell
    }
    
}

//自定义首页配图Cell
class HomePictureViewCell: UICollectionViewCell {
    
    //加载控件
    fileprivate lazy var imageView:UIImageView = {
        
        let imageV = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        //设置图片原始比例
        imageV.contentMode = .scaleAspectFill
        //裁剪超出范围
        imageV.clipsToBounds = true
        
        return imageV
        
    }()
    
    //模型数据
    var homePic: PictureModel?{
        
        didSet{
            if let urlStr = homePic?.thumbnail_pic{
                
                imageView.sd_setImage(with: URL(string:urlStr), placeholderImage: UIImage(named: "timeline_image_placeholder"))
            }
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //添加控件设置约束
    fileprivate func setupUI(){
        
        contentView.addSubview(imageView)
        
        imageView.snp.makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        
        
        
    }
    
    
    
}
